using System;
using System.Collections.Generic;
using System.Threading;

namespace SharpKeeperLib
{
    public class KObjectList : List<KObject>
    {
        public readonly String UniqueID = Guid.NewGuid().ToString();
        protected int Locks = 0;

        public void Lock()
        {
            lock (this)
            {
                Locks++;
                Monitor.Enter(this);
            }
        }

        public void Unlock()
        {
            lock (this)
            {
                if (Locks > 0)
                {
                    Locks--;
                    Monitor.Exit(this);
                }
            }
        }

        public void UnlockAll()
        {
            lock (this)
            {
                for (int i = 0; i < Locks; i++)
                {
                    Unlock();
                }
            }
        }

        public List<KObject> GetByType(Type type)
        {
            Lock();
            var res = new List<KObject>();

            foreach (var i in this)
            {
                if (i.GetType() == type)
                    res.Add(i);
            }

            Unlock();

            return res;
        }

        public List<KObject> GetByType(Type type, bool mayBeSubclass)
        {
            if (!mayBeSubclass)
                return GetByType(type);

            Lock();
            var res = new List<KObject>();

            foreach (var i in this)
            {
                if ((i.GetType() == type) || i.GetType().IsSubclassOf(type))
                    res.Add(i);
            }

            Unlock();

            return res;
        }

    }
}